import md5 from "js-md5";
const key = "VCByhZ#LUQVMvvE&5D";
// 参数排序
function dataSort(obj) {
  if (JSON.stringify(obj) == "{}" || obj == null) {
    return {};
  }
  let key = Object.keys(obj)?.sort();
  let newObj = {};
  for (let i = 0; i < key.length; i++) {
    newObj[key[i]] = obj[key[i]];
  }
  return newObj;
}

// 参数序列化
function dataSerialize(sortObj) {
  let strJoin = "";
  for (let key in sortObj) {
    strJoin += key + "=" + sortObj[key] + "&";
  }

  // return strJoin.substring(0, strJoin.length - 1)
  return strJoin;
}

export function signatureGenerate(obj = {}) {
  const timestamp = Math.floor(new Date().getTime() / 1000);
  obj["timestamp"] = timestamp;
  const sortObj = dataSort(obj);
  const str = dataSerialize(sortObj) + `key=${key}`;
  const sign = md5(str).toUpperCase();
  return {
    timestamp,
    sign,
  };
}
